package collectons工具类;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class sort对List集合进行自定义排序 {
    public static void main(String[] args) {

        List<Orange> list = new ArrayList<>();
        Orange orange1 = new Orange("红橘子",23.6);
        Orange orange2 = new Orange("青橘子",3455.0);
        Orange orange3 = new Orange("黄橘子",8975.5);
        Orange orange4 = new Orange("绿橘子",45.7);

        Collections.addAll(list,orange1,orange2,orange3,orange4);
        System.out.println(list);

//        就近原则，会调用自带的比较器
        Collections.sort(list, new Comparator<Orange>() {
            @Override
            public int compare(Orange o1, Orange o2) {
                if (o1.getPrice() > o2.getPrice()) return 1;
                if (o1.getPrice() < o2.getPrice()) return -1;
                return 0;
            }
        });
        System.out.println(list);
//        结果是升序排序，表明调用的是sort方法中定义的比较规则
    }
}

class Orange implements Comparable<Orange> {
    String name ;
    double price ;

    public Orange(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Orange{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}'+"\n";
    }

    @Override
    public int compareTo(Orange o) {
//        定义的规则与上面的相反
        if (this.getPrice() > o.getPrice()) return -1;
        if (this.getPrice() < o.getPrice()) return 1;
        return 0;
    }
}
